import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";
import router from "./router/index";
// 导入 Pinia 状态管理库
import { createPinia } from "pinia";
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";

// 导入 ElementPlus 的所有图标组件
import * as ElementPlusIconsVue from "@element-plus/icons-vue";

import PanelHead from "./components/panelHead.vue";

import { useAllMenuDataStore } from "@/store/menu.js";
//路由守卫
router.beforeEach((to, from) => {
  console.log("路由守卫:", to.path, "是否注册:", router.hasRoute(to.name));
  const token = localStorage.getItem("pz_token");
  console.log(`Navigating from ${from.path} to ${to.path}, token: ${token}`); // 调试信息
  //非登陆页token不存在
  if (!token && to.path !== "/login") {
    return "/login";
  } else if (token && to.path === "/login") {
    return "/";
  } else {
    return true;
  }
});

const app = createApp(App);
const pinia = createPinia();
// 1. 先安装 Pinia 插件
pinia.use(piniaPluginPersistedstate);
// 2. 安装 Pinia（必须在创建 store 实例之前）
app.use(pinia);
// 3. 现在可以安全地使用 store
const store = useAllMenuDataStore();
// 4. 安装路由
app.use(router);
//5. 注册全局组件,自动引入图标
Object.keys(ElementPlusIconsVue).forEach((key) => {
  app.component(key, ElementPlusIconsVue[key]);
});
// 全局注入
app.component("PanelHead", PanelHead);

// 7. 路由初始化操作应该在路由准备就绪后进行
router.isReady().then(() => {
  store.dynamicMenu(router, "refresh");
  // 6. 挂载应用
  app.mount("#app");
});
